<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">点击</button>
    <script>
        var oBtn = document.getElementById('btn')

        function myDebounce(handler, wait, immediate) { // 防抖的函数， 时间， 是否立即执行
            if (typeof handler !== 'function') throw new Error('handler must be function')
            if (typeof wait === 'undefined') wait = 1000
            if (typeof wait === 'boolean') {
                immediate = wait
                wait = 1000
            }
            if (typeof immediate === 'undefined') immediate = false
             // 防抖，就是再一个高频操作时，让他在一段时间内不再次执行
             // 如果要执行最后一次， 无论点击了多少次，前面的都无用
            let timer = null
            return function proxy(...args) {
                let self = this, init = immediate && !timer
                clearTimeout(timer)
                timer = setTimeout(()=> {
                    timer = null
                    !immediate ? handler.apply(self, [...args]) : null // apply传参传的是数组，call传参传的是字符串
                }, wait)
                init ? handler.apply(self, [...args]) : null
            }
        }   
       

        function click (ev) {
            console.log('点击了', this, ev)
            
        }
        oBtn.onclick = myDebounce(click, 500, false) 
        // oBtn.onclick = function (){
        //     let timer = null
        //     console.log(timer)
        // }
    </script>
</body>
</html>

